package com.openweixin.sheknows.interceptor;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.openweixin.sheknows.controller.BaseController;
import com.openweixin.sheknows.domain.User;
/**
 * 拦截器：拦截未登录的一些访问和无权限的一些访问
 * 注意事项：无
 * @author 刘思作
 * @version 1.0.0 2014-04-01
 * @since 1.0.0
 */
public class AuthInterceptor implements HandlerInterceptor {
	
	final static Logger logger = Logger.getLogger(AuthInterceptor.class);
	
	@Value("#{settings['url.public_uri']}")
	private String publicURI;
	@Value("#{settings['url.redirect']}")
	private String index;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if(isPublicURI(request)){
			return true;
		}
		
		User u = (User)request.getSession().getAttribute(BaseController.SESSION_USER);
		if(u != null){
			return true;
		}
		
		//String redirect = request.getContextPath() + index;
		//response.sendRedirect(redirect);
		return true;
	}
	private boolean isPublicURI(HttpServletRequest request){
		String[] accessible = publicURI.split(",");
		for (String uri : accessible) {
			if(uri.indexOf("*")!=-1){
				String regex = uri.replace("*",".+");
				if(Pattern.matches(request.getContextPath() + regex, request.getRequestURI())) {
					return true;
				}
			}else{
				if(request.getRequestURI().equals(request.getContextPath() + uri)){
					return true;
				}
			}
		}
		return false;
	}
	


	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}
	
}
